//
//  NightSetTableViewCell.m
//  花花时尚
//
//  Created by 霍文轩 on 15/9/1.
//  Copyright (c) 2015年 霍文轩. All rights reserved.
//

#import "NightSetTableViewCell.h"
#import "NightMode.h"

@interface NightSetTableViewCell()
@property (nonatomic,retain) UISwitch * nightSwitch;
@end

@implementation NightSetTableViewCell
- (void)dealloc
{
    [_nightSwitch release];
    [super dealloc];
}
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self){
        self.textLabel.text = @"夜间模式";
        self.textLabel.font = [UIFont boldSystemFontOfSize:17];
        self.textLabel.textColor = [NightMode nightModeON]?[UIColor lightGrayColor]:[UIColor blackColor];
        self.backgroundColor = [UIColor clearColor];
        
        self.nightSwitch = [[UISwitch alloc] init];
        [_nightSwitch addTarget:self action:@selector(setNightMode:) forControlEvents:UIControlEventValueChanged];
        
        // 如果userDefaults有nightON，就读取nightON设置为switch，如果没有，就把switch的状态设置为NightMode的初始状态
        NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        if([user objectForKey:@"nightON"] == nil){
            _nightSwitch.on = [NightMode nightModeON];
        }else{
            _nightSwitch.on = [[user objectForKey:@"nightON"] boolValue];
        }
        
        [self.contentView addSubview:_nightSwitch];
        [_nightSwitch release];
        
    }
    return self;
}
// 设置夜间模式的开关
-(void)setNightMode:(UISwitch *)nightSwitch{
    BOOL nightON = nightSwitch.on;
    // 根据开关的状态设置userDefaults，它可以永久保存数据，是一个字典，可以存储NSNumber，NSString，NSDate，NSArray，NSDictionary，BOOL
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    [user setObject:[NSNumber numberWithBool:nightON] forKey:@"nightON"];
    
    [self.delegate changeNightMode];
}
-(void)layoutSubviews{
    [super layoutSubviews];
    _nightSwitch.frame = CGRectMake(0, 0, 60, self.frame.size.height);
    _nightSwitch.center = CGPointMake(self.frame.size.width - 40, self.frame.size.height/2);
}
@end
